import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_用人单位对学校招聘服务的满意情况分布(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None
) -> Dict[str, Any]:
    """
    用人单位对学校招聘服务的满意情况分布 - 指标计算函数
    
    ## 指标说明
    该指标用于统计用人单位对学校招聘服务的满意度分布情况，计算每个选项的选择占比，
    其中"很满意"、"满意"和"基本满意"三项占比之和定义为整体满意度。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 5895,
        "questionnaire_ids": [11158, 11159]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok",
        "code": 0,
        "result": {
            "很满意": 0.45,
            "满意": 0.30,
            "基本满意": 0.15,
            "不满意": 0.07,
            "很不满意": 0.03,
            "满意度": 0.9
        }
    }
    ```
    """
    logger.info(f"开始计算指标: 用人单位对学校招聘服务的满意情况分布, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year, dy_target_items, split_tb_paper 
        FROM client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        split_tb_paper = project_info['split_tb_paper']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}, split_tb_paper={split_tb_paper}")

        # 2. 查询问卷信息
        questionnaire_sql = f"""
        SELECT id, dy_target 
        FROM wt_template_customer 
        WHERE id IN ({','.join(['%s'] * len(questionnaire_ids))})
        """
        questionnaires = db.fetchall(questionnaire_sql, tuple(questionnaire_ids))
        if not questionnaires:
            raise ValueError(f"未找到问卷ID集合={questionnaire_ids}的配置信息")
        
        logger.info(f"查询到问卷信息: {questionnaires}")

        # 3. 过滤调研对象为EMPLOYER的问卷
        employer_questionnaire_ids = [q['id'] for q in questionnaires if q['dy_target'] == 'EMPLOYER']
        if not employer_questionnaire_ids:
            raise ValueError("未找到目标调研对象(EMPLOYER)的问卷ID")
            
        logger.info(f"找到EMPLOYER问卷ID: {employer_questionnaire_ids}")

        # 4. 查询问题信息
        question_sql = """
        SELECT id, wt_code, wt_obj 
        FROM wt_template_question_customer 
        WHERE cd_template_id = %s AND wt_code = 'T00000462' AND is_del = 0
        """
        question_info = db.fetchone(question_sql, (employer_questionnaire_ids[0],))
        if not question_info:
            raise ValueError("未找到指定问题编码(T00000462)的问题信息")
            
        logger.info(f"找到问题信息: {question_info['id']}")

        # 5. 解析问题选项
        wt_obj = json.loads(question_info['wt_obj'])
        options = {item['key']: item['val'] for item in wt_obj['itemList']}
        logger.info(f"问题选项: {options}")

        # 6. 构建动态表名
        answer_table = f"re_dy_paper_answer_{split_tb_paper}"

        # 7. 查询答案数据
        answer_sql = f"""
        SELECT
            SUM(c1) as c1_sum,
            SUM(c2) as c2_sum,
            SUM(c3) as c3_sum,
            SUM(c4) as c4_sum,
            SUM(c5) as c5_sum,
            (SUM(c1)+SUM(c2)+SUM(c3)+SUM(c4)+SUM(c5)) as total
        FROM {answer_table}
        WHERE cd_template_id = %s AND wid = %s AND ans_true = 1
        """
        answer_data = db.fetchone(answer_sql, (employer_questionnaire_ids[0], question_info['id']))
        if not answer_data or not answer_data['total']:
            raise ValueError("未找到有效的答案数据或样本量为0")
        
        logger.info(f"答案数据: {answer_data}")

        # 8. 计算各选项占比
        result = {
            "很满意": round(answer_data['c1_sum'] / answer_data['total'], 4),
            "满意": round(answer_data['c2_sum'] / answer_data['total'], 4),
            "基本满意": round(answer_data['c3_sum'] / answer_data['total'], 4),
            "不满意": round(answer_data['c4_sum'] / answer_data['total'], 4),
            "很不满意": round(answer_data['c5_sum'] / answer_data['total'], 4),
            "满意度": round((answer_data['c1_sum'] + answer_data['c2_sum'] + answer_data['c3_sum']) / answer_data['total'], 4)
        }

        logger.info(f"指标 '用人单位对学校招聘服务的满意情况分布' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": result
        }

    except Exception as e:
        logger.error(f"计算指标 '用人单位对学校招聘服务的满意情况分布' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 用人单位对学校招聘服务的满意情况分布",
            "code": 500,
            "error": str(e)
        }